<!--
 * @Description: 结算账单记录导入
 * @Author: py
 * @Date: 2024-03-03
-->
<script setup lang="ts" name="record-import">
// import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import type { UploadFile, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useChargeSettleStoreWithOut } from '@/store/modules/charge-settle'
import { getAccessToken } from '@fl/logics/authentication'
// import { chargeAccountListApi, freezePayListApi } from '@fl/api/charge-settle'
// import { SearchTable } from '@fl/components'
// import { formatTime } from '@fl/utils'
// import { uploadExcel } from '@fl/api/xf-api/label-manage'
import { useRouter } from 'vue-router'

const chargeSettleStore = useChargeSettleStoreWithOut()
const router = useRouter()

// const { query } = useRoute()
// const { importType } = query

const uploadRef = ref<UploadInstance>()
const baseUrl = import.meta.env.DEV ? import.meta.env.VITE_API_BASE_PATH : window.location.origin
// const uploadUrl = `${baseUrl}/clearing-api/v1/sycn/${importType === 'chargeList' ? 'sycnSettlement' : 'sycnOrderParking'}`
const uploadUrl = `${baseUrl}/clearing-api/v1/sycn/importAll`
const token = getAccessToken()
const uploadHeaders = {
    Authorization: import.meta.env.VITE_STORE_PREFIX === 'AnJuOrg' && window.localStorage.getItem('appKey') ? null : `Bearer ${token}`,
}
const fileList = ref<UploadFile[]>([])
const uploadStatus = ref('beforeUpload') // beforeUpload | uploading | uploadSuccess | uploadFail
const progress = ref(0)
type FileInfo = {
    name?: string
    size?: number
}
const currentFile = ref<FileInfo>({})
const importCount = ref(0) // 导入数据总数

const isUploading = computed(() => uploadStatus.value === 'uploading')
const isSuccess = computed(() => uploadStatus.value === 'uploadSuccess')
const isFail = computed(() => uploadStatus.value === 'uploadFail')
const hasFile = computed(() => fileList.value.length > 0)

// 文件大小格式化
function formatFileSize(size: number): string {
    if (!size) {
        return '0 B'
    }

    if (size < 1024) {
        return `${size} B`
    }
    else if (size < 1024 * 1024) {
        return `${(size / 1024).toFixed(2)} KB`
    }
    else {
        return `${(size / (1024 * 1024)).toFixed(2)} MB`
    }
}

/**
// 上传前的检查; 设置不自动上传时 不执行该钩子
function handleBeforeUpload(rawFile: UploadRawFile) {
    console.log("🚀 ~ handleBeforeUpload ~ rawFile:", rawFile);
    return true
}

// const formLoading = ref(false)
function handleHttpRequest(params) {
    const file = params.file
    const fileType = file.type
    const isExcel = fileType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || fileType.includes('.xlsx')
    const isLt20M = file.size / 1024 / 1024 < 20
    if (!isExcel) {
        ElMessage.error('只能上传.xls,.xlsx格式的Excel文件!')
        return
    }
    if (!isLt20M) {
        ElMessage.error('只能上传小于20M的文件')
        return
    }
    // 根据后台需求数据格式
    const formData = new FormData()
    // 文件对象
    formData.append('file', file)
    // handleSubmit(formData)
    uploadExcel(formData).then((res) => {
        if (res.code === 200) {
            // formLoading.value = false
            ElMessage.success(res.msg)
            // doSearch()
        }
        else {
            ElMessage.error(res.msg)
        }
    })
}
*/

const handleChange: UploadProps['onChange'] = (uploadFile) => {
    // console.log("🚀 handleChange~ uploadFile:", uploadFile);
    if (uploadFile.status === 'success') {
        fileList.value = []
        currentFile.value = {}
    }
    else {
        if (uploadFile.status === 'fail') {
            uploadFile.status = 'ready'
            uploadFile.percentage = 0
        }
        fileList.value = [uploadFile]
        currentFile.value = {
            name: uploadFile.name,
            size: uploadFile.size,
        }
    }
}
const handleProgress: UploadProps['onProgress'] = (evt) => {
    // console.log('🚀 handleProgress~ evt:', evt)
    progress.value = Math.floor(evt.percent)
}
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    uploadRef.value!.handleStart(file)
    // console.log("🚀 ~ onExceed:", files);
}
const handleSuccess: UploadProps['onSuccess'] = (res, uploadFile) => {
    // console.log("🚀 handleSuccess~ response:", res);
    // console.log("🚀 handleSuccess~ uploadFile:", uploadFile);
    if (res.code === 200) {
        uploadStatus.value = 'uploadSuccess'
        progress.value = 0
        importCount.value = res.data
        ElMessage.success('导入成功')
        chargeSettleStore.updateStatementRecord()
    }
    else {
        uploadStatus.value = 'uploadFail'
        progress.value = 0
        uploadFile.status = 'fail'
        ElMessage.error(res.msg)
    }
}
const handleError: UploadProps['onError'] = () => {
    // console.log('🚀 handleError~ errRes:', errRes)
    // console.log("🚀 handleError~ uploadFile:", uploadFile);
    ElMessage.error('导入失败')
    uploadStatus.value = 'uploadFail'
    progress.value = 0
}

// 手动触发上传
function submitUpload() {
    const [file] = fileList.value
    if (!file)
        return

    // 文件类型验证
    const contentTypeArr = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
    if (!contentTypeArr.includes(file.raw!.type)) {
        ElMessage.error('只能上传.xls,.xlsx格式的Excel文件!')
        return false
    }

    // 文件限制大小
    if (file.size! > 20 * 1024 * 1024) {
        ElMessage.error('所选文件大小不能超过20M')
        return false
    }

    uploadStatus.value = 'uploading'
    uploadRef.value!.submit()
}

function handleCancel() {
    uploadRef.value?.clearFiles()
    router.back()
}

function lookImportDatas() {
    chargeSettleStore.updateStatementRecord()
    handleCancel()
}

/**
function formatDate({ cellValue }) {
    return formatTime(cellValue, 'yyyy-MM-dd')
}
function formatPrice({ cellValue }) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${Number.parseFloat(cellValue).toFixed(2)}`
}
const chargeGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'orderCode', minWidth: 140, title: '订单ID' },
        { field: 'operatorName', minWidth: 160, title: '商户名称' },
        { field: 'stationName', minWidth: 180, title: '站点名称' },
        { field: 'billGenerationTime', formatter: formatDate, title: '结算账单日期', width: 120 },
        { field: 'chargeStartTime', title: '充电开始时间', width: 160 },
        { field: 'chargeEndTime', title: '充电完成时间', width: 160 },
        { field: 'chargeAmount', minWidth: 120, title: '订单充电量' },
        { align: 'right', field: 'totalAmount', formatter: formatPrice, title: '实收总金额', width: 120 },
        { align: 'right', field: 'chargeFee', formatter: formatPrice, title: '实收电费', width: 120 },
        { align: 'right', field: 'serviceFee', formatter: formatPrice, title: '实收服务费', width: 120 },
        { align: 'right', field: 'platformServiceFee', formatter: formatPrice, title: '平台技术服务费', width: 135 },
    ],
    data: [],
    loading: false,
    maxHeight: 450,
    minHeight: 250,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const chargeTablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function getChargeList() {
    chargeGridOptions.loading = true

    const oParams = {
        pageNum: chargeTablePage.currentPage,
        pageSize: chargeTablePage.pageSize,
    }

    chargeAccountListApi(oParams).then((res) => {
        const { records, total } = res
        chargeTablePage.total = +total
        chargeGridOptions.data = records
    }).finally(() => {
        chargeGridOptions.loading = false
    })
}
// getChargeList()

const chargePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    chargeTablePage.currentPage = currentPage
    chargeTablePage.pageSize = pageSize
    getChargeList()
}

const freezePayGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'operatorName', minWidth: 160, title: '商户名称' },
        { field: 'stationName', minWidth: 180, title: '站点名称' },
        { field: 'orderCode', minWidth: 140, title: '订单ID' },
        { field: 'changeType', minWidth: 120, title: '变动类型' },
        // { field: 'contractId', minWidth: 140, title: '合同ID' },
        // { field: 'applicationId', minWidth: 140, title: '发票申请单ID' },
        // { field: 'updateTime', title: '操作时间', width: 160 },
        { field: 'billGenerationTime', formatter: formatDate, title: '结算日期', width: 120 },
        { align: 'right', field: 'parkingFee', formatter: formatPrice, title: '金额', width: 120 },
        { field: 'feeType', minWidth: 140, title: '费用类型' },
    ],
    data: [],
    loading: false,
    maxHeight: 450,
    minHeight: 250,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const freezePayTablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function getFreezePayList() {
    freezePayGridOptions.loading = true

    const oParams = {
        pageNum: freezePayTablePage.currentPage,
        pageSize: freezePayTablePage.pageSize,
    }

    freezePayListApi(oParams).then((res) => {
        const { records, total } = res
        freezePayTablePage.total = +total
        freezePayGridOptions.data = records
    }).finally(() => {
        freezePayGridOptions.loading = false
    })
}
// getFreezePayList()

const freezePayPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    freezePayTablePage.currentPage = currentPage
    freezePayTablePage.pageSize = pageSize
    getFreezePayList()
}
*/
</script>

<template>
    <div v-loading="isUploading"
         class="page-container"
         element-loading-text="正在导入中，请稍等..."
         element-loading-background="rgba(255, 255, 255, 0.9)"
    >
        <el-button class="mb-20"
                   @click="$router.back"
        >
            返回列表
        </el-button>

        <div class="px-24">
            <h2 class="module-title">
                导入说明
            </h2>

            <div class="content-explain">
                <div class="description-item">
                    <div class="description-label">
                        导入数据来源：
                    </div>

                    <div class="description-content">
                        "小桔充电"平台--财务--账单--汇总账单
                    </div>
                </div>

                <div class="description-item">
                    <div class="description-label">
                        导入步骤：
                    </div>

                    <div class="description-content">
                        <p>1、自上述来源中导出结算日期为当日的"汇总账单"记录。</p>

                        <p>2、导出的EXCEL不用处理，直接在此板块进行上传。</p>

                        <p>3、系统会自动识别EXCEL中"充电账单明细"及"冻结及赔付账单明细"进行导入。</p>
                    </div>
                </div>
            </div>

            <h2 class="module-title">
                导入EXCEL
            </h2>

            <div class="import-main">
                <template v-if="isSuccess">
                    <div class="status-box mb-16">
                        <img src="./images/icon_success.png"
                             alt="success"
                             class="icon-status"
                        >

                        <p class="text-status">
                            导入完成
                        </p>

                        <!-- <p class="text-desc">
                            已成功导入{{ importCount }}条数据
                        </p> -->
                    </div>

                    <div class="btns-footer">
                        <el-button @click="uploadStatus = 'beforeUpload'">
                            再次导入
                        </el-button>

                        <el-button type="primary"
                                   @click="handleCancel"
                        >
                            查看导入数据
                        </el-button>
                    </div>
                </template>

                <template v-else-if="isFail">
                    <div class="status-box mb-16">
                        <img src="./images/icon_fail.png"
                             alt="failture"
                             class="icon-status"
                        >

                        <p class="text-status">
                            导入失败
                        </p>

                        <!-- <p class="text-desc">
                            已成功导入xx条数据，<span class="text-#ff3e24">失败 20 条</span>
                        </p>

                        <p class="text-desc">
                            可编辑下面错误信息列表，重新导入
                        </p> -->
                    </div>

                    <!-- <SearchTable v-if="importType === 'chargeList'"
                                 v-bind="chargeGridOptions"
                                 v-model:pager="chargeTablePage"
                                 @page-change="chargePageChange"
                    />

                    <SearchTable v-else
                                 v-bind="freezePayGridOptions"
                                 v-model:pager="freezePayTablePage"
                                 @page-change="freezePayPageChange"
                    /> -->

                    <div class="btns-footer">
                        <el-button @click="handleCancel">
                            取消
                        </el-button>

                        <el-button @click="lookImportDatas">
                            查看导入数据
                        </el-button>

                        <el-button type="primary"
                                   @click="uploadStatus = 'beforeUpload'"
                        >
                            重新导入
                        </el-button>
                    </div>
                </template>

                <template v-else>
                    <!-- accept="xls,.xlsx,.xlsm,.xlsb,.csv" -->
                    <!-- :http-request="handleHttpRequest" -->
                    <el-upload ref="uploadRef"
                               class="upload-wrapper mb-16"
                               :action="uploadUrl"
                               :headers="uploadHeaders"
                               accept=".xls,.xlsx"
                               :auto-upload="false"
                               drag
                               :file-list="fileList"
                               :limit="1"
                               :on-change="handleChange"
                               :on-progress="handleProgress"
                               :on-exceed="handleExceed"
                               :on-success="handleSuccess"
                               :on-error="handleError"
                               :show-file-list="false"
                               :disabled="isUploading"
                    >
                        <div v-if="isUploading"
                             class="status-content"
                        >
                            <img src="./images/icon_excel.png"
                                 alt="excelsheet"
                                 class="icon-excel"
                            >

                            <div class="file-info mb-16">
                                {{ currentFile.name }} ({{ formatFileSize(currentFile.size!) }})
                            </div>

                            <!-- <el-progress :percentage="progress"
                                         :stroke-width="4"
                                         color="#235fc4"
                            /> -->
                        </div>

                        <div v-else-if="hasFile"
                             class="status-content"
                        >
                            <img src="./images/icon_excel.png"
                                 alt="excelsheet"
                                 class="icon-excel"
                            >

                            <div class="file-info mb-16">
                                {{ currentFile.name }} ({{ formatFileSize(currentFile.size!) }})
                            </div>
                            <!-- <template #trigger>
                                <el-button>重新选择</el-button>
                            </template> -->
                        </div>

                        <div v-else
                             class="status-content"
                        >
                            <el-icon class="el-icon--upload">
                                <upload-filled />
                            </el-icon>

                            <p class="tips-action">
                                将文件拖动到此区域
                            </p>

                            <p class="tips-warning">
                                请上传 <span class="tips-strong">20M</span> 以内 Excel 文件
                            </p>
                        </div>
                    </el-upload>

                    <div class="btns-footer">
                        <el-button @click="handleCancel">
                            取消
                        </el-button>

                        <el-button type="primary"
                                   :disabled="isUploading || !hasFile"
                                   @click="submitUpload"
                        >
                            导入
                        </el-button>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
@import '../custom.less';

.page-container {
    min-height: 100%;
    padding: 20px;
    background-color: #fff;
    border-radius: 3px 3px 0 0;
}

.module-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 16px;
}

// 导入说明
.content-explain {
    background-color: #f2f3f5;
    padding: 12px 16px;
    border-radius: 3px;
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color: #1d2129;
    margin-bottom: 20px;
}

.import-main {
    display: flex;
    flex-direction: column;
    align-items: center;

    :deep(.el-tabs) {
        width: 100%;
    }
}

// 说明条款
.description-item {
    display: flex;
    margin-bottom: 8px;

    &:last-child {
        margin-bottom: 0;
    }

    .description-label {
        width: 7em;
        display: inline-flex;
        flex: 0 0 auto;
        justify-content: flex-end;
        margin-right: 8px;
    }

    .description-content {
        flex: 1;
    }
}

.upload-wrapper {
    width: 500px;
    // margin: 0 auto;

    .tips-action {
        font-size: 16px;
        line-height: 22px;
        font-weight: 400;
        color: #1d2129;
    }

    .tips-warning {
        font-size: 14px;
        line-height: 22px;
        font-weight: 400;
        color: #86909c;
    }

    .tips-strong {
        font-size: 16px;
        line-height: 22px;
        color: #1d2129;
    }
}

:deep(.el-upload:focus) {
    // border-color: #e5e6eb;
    color: unset;

    .el-upload-dragger {
        border-color: #e5e6eb;
    }
}

:deep(.el-upload-dragger) {
    padding: 62px 30px;
    background-color: #f7f8fa;
    border-radius: 8px;
    border: 1px solid #e5e6eb;

    .el-icon--upload {
        font-size: 64px;
        color: #c9cdd4;
        margin-bottom: 0;
    }
}

.status-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 4px;

    .icon-excel {
        width: 56px;
        height: 56px;
    }

    .file-info {
        font-size: 16px;
        line-height: 22px;
        font-weight: 400;
        color: #4e5969;
    }
}

:deep(.el-progress) {
    width: 100%;
}

.status-box {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 4px;
    height: 98px;
    padding-left: 122px;

    .icon-status {
        position: absolute;
        left: 0;
        width: 98px;
        height: 98px;
    }

    .text-status {
        font-size: 18px;
        line-height: 25px;
        color: #1d2129;
    }

    .text-desc {
        font-size: 14px;
        line-height: 20px;
        font-weight: 400;
        color: #1d2129;
    }
}

.btns-footer {
    padding: 12px 0;
}
</style>
